import { useState } from 'react';
import { useDispatch } from 'react-redux';
import { useDebounce, useHandler } from '@cfe/hooks';
import { AutoComplete } from 'antd';
import { camelizeKeys } from 'humps';

import { requestWithoutCache } from '@/utils/request';

const GroupTagSearchItem = ({ setGroupTagItem, openModal }) => {
  const [options, setOptions] = useState([]);
  const [value, setValue] = useState('');
  const dispatch = useDispatch();

  const handleSearch = useDebounce((name) => {
    requestWithoutCache(`/api/dmp/market/tag_group?group_name=${name}`).then(
      (res) => {
        if (res.status === 0) {
          const data = camelizeKeys(res.data);
          setOptions(data);
          return data;
        }
      },
    );
  }, 300);

  const handleSelect = useHandler((groupId) => {
    const selectedGroupTag = options.find(
      (option) => option.groupId === groupId,
    );
    setGroupTagItem(selectedGroupTag);
    setValue(selectedGroupTag.groupName);
    dispatch({ type: 'label/loadGroupTag', payload: { dimId: 330002 } });
    openModal();
  });

  return (
    <>
      <AutoComplete
        style={{ marginLeft: '30px', width: '400px' }}
        options={options.map(({ groupId, groupName }) => ({
          label: groupName,
          value: groupId,
        }))}
        onSelect={handleSelect}
        onSearch={handleSearch}
        onChange={setValue}
        value={value}
        placeholder="搜索标签"
      />
    </>
  );
};

export default GroupTagSearchItem;
